#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

#include <unistd.h>

#include <sys/types.h>
#include <sys/socket.h>

#include <sys/shm.h>
#include <pthread.h>

#include "server.h"
#include "mutexs.h"

#define REQ_DATA_SIZE   32
#define HDR_DATA_SIZE   128
int zgbfd, srvfd;

void *x_read_request(void *x_arg);
/****************************
 *函数名：x_thread_cam
 *
 *功能：调用视频采集模块
 *
 *参数：无
 *
 * 返回值：无
 * ****************************/
void *x_thread_cam()
{
	int x_ret = -1;
	while (x_ret < 0 )
    {
		x_ret = camera_on();//调用视频采集模块
		sleep(3);
	}
	return (void *)0;
}

/***********************************
 *函数名：x_thread_srv
 *
 *功能：创建线程连接服务器
 *
 *参数：无
 *
 *返回值：无
 * *************************************/
void *x_thread_srv()
{
	int *x_tempfd;
	int x_connfd;
	pthread_t x_requst_tid;//服务器读取客户端线程号
	
	int x_sockfd = x_server_init();
	if(0>x_sockfd)
    {
		printf("init_server failed!\n");
		pthread_exit(NULL);
	}
	while(1) 
    {
        if ((x_connfd = x_server_wait_connect(x_sockfd)) != -1) 
        {
			x_tempfd = malloc(sizeof(int));
			if (!x_tempfd) 
            {
				fprintf(stderr, "server->malloc: malloc failure\n");
				close(x_connfd);
				close(x_sockfd);
			}
			*x_tempfd = x_connfd;
			int x_ret = pthread_create(&x_requst_tid, NULL, x_read_request, x_tempfd);
			if (x_ret) 
            {
				errno = x_ret;
				perror("server->thread");
				close(x_connfd);
				close(x_sockfd);
			} 
            else
				printf("server->thread: create client thread success\n");
		}
	}
}

/**********************************
 *函数名：x_read_request
 * 
 *功能：客户端请求线程处理函数
 *
 *参数：通信套接字
 *
 *返回值：成功返回0，失败返回-1
 * ***********************************/
void *x_read_request(void *x_arg)
{
	int x_ret;
	int x_connfd = *(int *)x_arg;
	char x_request[REQ_DATA_SIZE] = {0};
	char x_response[HDR_DATA_SIZE] = {0};
	while(1)
    {
		memset(x_request, 0, sizeof(x_request));
		x_ret = x_recv(x_connfd, x_request, sizeof(x_request));
		if (x_ret <= 0)
			return (void *)-1;
		fprintf(stdout, "%s", x_request);
		if (strstr(x_request, "PIC_SEND") != NULL) 
        {
			pthread_mutex_lock(&cam_mutex);
			snprintf(x_response, sizeof(x_response), "%dlen", jpg->jpg_size);
			x_ret =x_send_nbytes(x_connfd, x_response, sizeof(x_response));
			if (x_ret != sizeof(x_response)) 
            {
				fprintf(stderr, "server->write: send response failed\n");
				return (void *)-1;
			}
			printf("%s\n", x_response);
			x_ret = x_send_nbytes(x_connfd, jpg->jpg_buf, jpg->jpg_size);
			if (x_ret != jpg->jpg_size) 
            {
				fprintf(stderr, "server->write: send response failed\n");
				return (void *)-1;
			}
			printf("send pic\n");
			pthread_mutex_unlock(&cam_mutex);
        }
    }

	return (void *)0;
}
